Event.observe(window, 'load', function(event) {

  setupCalendar('task_formatted_begin_at');
  setupCalendar('task_formatted_end_at');

  setupSelectableInput('name_select', 'name');

  var form = $('save-workers-form');
  form.observe('submit', function(event) {
    var params = workerParams();
    for (var name in params) {
      var input = new Element('input', { type: 'hidden', name: name, value: params[name] });
      form.appendChild(input);
    }
  });

});

/*
 * 編集
 */
function toggleEdit() {
  $('show-task').toggle();
  $('edit-task').toggle();
}


/*
 * 担当者保存
 */

function workerParams() {
  var params = {};
  Element.childElementNodes('workers-body').each(function(row) {
    if (row.nodeType != Node.ELEMENT_NODE) return;

    var userId = row.id.split('-')[1];
    var periods = [];
    var begin_at;
    var last;
    cells = Element.childElementNodes(row);
    cells.each(function(cell, index) {
      if (index == 0) return;
      var date = cellDate(cell);
      if (!begin_at) {
        if (isActiveCell(cell))
          begin_at = date;
      } else {
        if (!isActiveCell(cell)) {
          periods.push(begin_at + ',' + last);
          begin_at = null;
        }
      }
      last = date;
    });
    if (begin_at)
      periods.push(begin_at + ',' + last);
    params['workers[' + userId + ']'] = periods.join(';');
  });
  return params;
}

function isActiveCell(cell) {
  return cell.className == 'active';
}

function cellDate(cell) {
  return cell.id.split('_')[1];
}

/*
 * ドラッグイベント
 */

var changed = false;
var dragging = false;
var currentActive = true;

function setCurrentActive(cell) {
  cell.className = currentActive ? 'active' : '';
  changed = true;
}

function onDayCellMouseDown(event) {
  dragging = true;
  var cell = Event.element(event);
  currentActive = !isActiveCell(cell)
  setCurrentActive(cell);
  Event.stop(event);
}

function onDayCellMouseMove(event) {
  if (dragging) {
    setCurrentActive(Event.element(event));
    Event.stop(event);
  }
}

function onMouseUp(event) {
  dragging = false;
  if (changed) {
    $('save-workers-submit').disabled = false;
    $('save-workers-submit').focus();
  }
  changed = false;
}

Event.observe(document, 'mouseup', onMouseUp);
  
